package com.sykj.manage.shiro;

import java.util.HashSet;

import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.sykj.manage.model.SysUser;
import com.sykj.manage.model.Sys_User;
import com.sykj.manage.service.SysUserService;


public class AuthRealm2 extends AuthorizingRealm{

	@Autowired
	SysUserService sysUserService;
	
	/**
	 * 这是认证方法
	 * (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		//arg0 前端输入的用户名密码
		UsernamePasswordToken userToken = (UsernamePasswordToken) arg0;
		SysUser sysUser = new SysUser();
		sysUser.setAccount(userToken.getUsername());
		sysUser.setPassword(new String(userToken.getPassword()));
		SysUser user = sysUserService.getUserName(sysUser);
		SimpleAuthenticationInfo aInfo = null;
		if (user!=null) {
			String realmname = getName();
			ByteSource credentialsSalt = ByteSource.Util.bytes(user.getAccount());
			//创建认证信息对象
			aInfo = new SimpleAuthenticationInfo(user.getAccount(),user.getPassword(),credentialsSalt,realmname);
		}else {
			throw new UnknownAccountException("该用户不存在！！");
		}
		return aInfo;//返回认证信息对象aInfo
	}


	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		//创建角色集合
				Set<String> roles = new HashSet<String>();
				Object principal = arg0.getPrimaryPrincipal();
				if (principal.equals("aa")) {
					roles.add("user");
				}else if (principal.equals("11")) {
					roles.add("admin");
				}
				//System.out.println(roles+"==============="+principal);
				SimpleAuthorizationInfo aInfo = 
						new SimpleAuthorizationInfo(roles);
				
				return aInfo;
	}

}
